package day5.demo2_顺序执行;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class 按序显示ABC {
	static Lock loc=new ReentrantLock();
	static int num=0;//用来标识当前轮到哪个线程执行
	//标识某一线程的等待与通知
	static Condition[] arr = {loc.newCondition(),loc.newCondition(),loc.newCondition()};
	//参数决定哪个线程应该阻塞，0，1，2
	static void task(int i)throws Exception{
		loc.lock();
		//判断是否轮到当前线程
		if(num!=i){
			arr[i].await();
		}
		System.out.println((char)('A'+i));
		//唤醒B线程
		if(++num==3){
			num = 0;
			System.out.println("-------------------------");
		}
		arr[num].signal();
		loc.unlock();
	}

	public static void main(String[] args)throws Exception{
		new Thread(() -> {
			while (true){
				try {
					task(2);
				} catch (Exception e) {}
			}
		}).start();

		new Thread(() -> {
			while (true){
				try {
					task(1);
				} catch (Exception e) {}
			}
		}).start();

		new Thread(() -> {
			while (true){
				try {
					task(0);
				} catch (Exception e) {}
			}
		}).start();
	}
}